package cn.com.test.testspringboot.nettyTest.groupChat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @author wangyw
 */
public class GroupChatServer {
    private int port;

    public GroupChatServer(int port) {
        this.port = port;
    }

    public void run() {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bt = new ServerBootstrap();
            bt.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    // 服务端可连接队列数
                    .option(ChannelOption.SO_BACKLOG, 128)
                    /**
                     * 它启用了 TCP 的保活机制。当启用 SO_KEEPALIVE 时，
                     * 如果在两次成功通信之间的时间超过了系统定义的保活时间（通常是2小时），
                     * 则会发送一个保活探测包。这个探测包用于检查连接是否仍然有效。
                     * */
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    // 给指定的pipeline设置相关的handler
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 拿到pipeline
                            ChannelPipeline pipeline = ch.pipeline();
                            // 向pipeline加入一个解码器(接受的时候用)
                            pipeline.addLast("decode", new StringDecoder());
                            // 向pipeline加入一个编码器(发送的时候用)
                            pipeline.addLast("encoder", new StringEncoder());
                            // 向pipeline加入自己的业务处理handler
                            pipeline.addLast(new GroupChatServerHandler());

                        }
                    });
            System.out.println("netty 服务器启动了...");
            ChannelFuture future = bt.bind(port).sync();
            // 监听关闭事件
            future.channel().closeFuture().sync();
        }catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }


    }

    public static void main(String[] args) {
        new GroupChatServer(7000).run();
    }
}
